import { _decorator, Component, Node, UITransform, EventTouch, Vec2, Vec3, Input, input, view, Color, Sprite } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('JoystickController')
export class JoystickController extends Component {
    @property(Node)
    private joystickBackground: Node = null;
    
    @property(Node)
    private joystickKnob: Node = null;
    
    @property(Node)
    private touchBall: Node = null;
    
    @property
    private maxRadius: number = 100;
    
    @property
    private deadzone: number = 10;

    @property
    private touchBallRadius: number = 20;

    @property
    private touchBallColor: Color = new Color(255, 255, 255, 128);
    
    private _touchId: number = -1;
    private _isTouching: boolean = false;
    private _direction: Vec2 = new Vec2();
    private _backgroundRect: UITransform = null;
    private _originPosition: Vec3 = new Vec3();
    private _moveVector: Vec2 = new Vec2(0, 0);
    private _uiRootPosition: Vec3 = new Vec3();
    
    start() {
        // 获取背景矩形组件用于定位计算
        this._backgroundRect = this.joystickBackground.getComponent(UITransform);
        
        // 存储原始位置
        this._originPosition = this.joystickBackground.position.clone();
        
        // 注册触摸事件
        this._registerTouchEvents();

        // 创建触摸跟随小球
        this._createTouchBall();
        
        // 获取UI根节点位置
        this._uiRootPosition = this.node.position.clone();
    }
    
    // 注册触摸事件处理函数
    private _registerTouchEvents() {
        // 触摸开始
        this.node.on(Input.EventType.TOUCH_START, this._onTouchStart, this);
        
        // 触摸移动
        this.node.on(Input.EventType.TOUCH_MOVE, this._onTouchMove, this);
        
        // 触摸结束/取消
        this.node.on(Input.EventType.TOUCH_END, this._onTouchEnd, this);
        this.node.on(Input.EventType.TOUCH_CANCEL, this._onTouchEnd, this);
    }

    // 创建触摸跟随的小球
    private _createTouchBall() {
        // 如果已经有小球节点，就直接使用
        if (this.touchBall) {
            // 确保小球有Sprite组件
            let sprite = this.touchBall.getComponent(Sprite);
            if (!sprite) {
                sprite = this.touchBall.addComponent(Sprite);
            }
            // 设置小球的颜色和透明度
            sprite.color = this.touchBallColor;
            
            // 确保有UITransform组件
            let transform = this.touchBall.getComponent(UITransform);
            if (!transform) {
                transform = this.touchBall.addComponent(UITransform);
            }
            transform.width = this.touchBallRadius * 2;
            transform.height = this.touchBallRadius * 2;
            
            // 默认显示小球，放置在摇杆中心位置
            this.touchBall.active = true;
            this.touchBall.setPosition(this.joystickKnob.position);
            return;
        }

        // 如果没有预设的小球节点，就创建一个
        this.touchBall = new Node("TouchBall");
        this.joystickBackground.addChild(this.touchBall); // 将小球添加为摇杆背景的子节点
        
        // 添加UI变换组件以设置大小
        const transform = this.touchBall.addComponent(UITransform);
        transform.width = this.touchBallRadius * 2;
        transform.height = this.touchBallRadius * 2;
        
        // 添加精灵组件
        const sprite = this.touchBall.addComponent(Sprite);
        sprite.color = this.touchBallColor;
        
        // 默认显示小球，放置在摇杆中心位置
        this.touchBall.active = true;
        this.touchBall.setPosition(this.joystickKnob.position);
    }
    
    private _onTouchStart(event: EventTouch) {
        if (this._isTouching) return;
        
        // 存储触摸ID
        this._touchId = event.getID();
        this._isTouching = true;
        
        // 获取UI坐标系中的触摸位置
        const touchPos = event.getUILocation();
        const visibleSize = view.getVisibleSize();
        
        // 计算触摸位置相对于屏幕中心的偏移
        const touchPosInScene = new Vec3(
            touchPos.x - visibleSize.width / 2,
            touchPos.y - visibleSize.height / 2,
            0
        );
        
        // 更新摇杆位置
        this.joystickBackground.setPosition(touchPosInScene);
        this.joystickKnob.setPosition(0, 0, 0);
        
        // 更新小球位置，初始放在摇杆位置
        if (this.touchBall) {
            this.touchBall.setPosition(0, 0, 0);
        }
        
        this._moveVector.set(Vec2.ZERO);
    }
    
    private _onTouchMove(event: EventTouch) {
        if (!this._isTouching || event.getID() !== this._touchId) return;
        
        // 获取UI坐标系中的触摸位置
        const touchPos = event.getUILocation();
        const visibleSize = view.getVisibleSize();
        
        // 计算触摸位置相对于屏幕中心的偏移
        const touchPosInScene = new Vec3(
            touchPos.x - visibleSize.width / 2,
            touchPos.y - visibleSize.height / 2,
            0
        );
        
        // 计算背景中心在场景中的位置
        const center = this.joystickBackground.position.clone();
        
        // 计算触摸到中心的方向
        const direction = new Vec2(
            touchPosInScene.x - center.x,
            touchPosInScene.y - center.y
        );
        
        // 计算距离
        const distance = direction.length();
        
        // 归一化方向
        if (distance > 0) {
            direction.multiplyScalar(1 / distance);
        }
        
        // 应用死区
        if (distance < this.deadzone) {
            this._moveVector.set(Vec2.ZERO);
            this.joystickKnob.setPosition(0, 0, 0);
            
            // 小球位置重置到中心
            if (this.touchBall) {
                this.touchBall.setPosition(0, 0, 0);
            }
            return;
        }
        
        // 设置移动向量(归一化)
        this._moveVector.set(direction);
        
        // 限制摇杆位置在最大半径内
        let knobPos = new Vec3();
        
        if (distance > this.maxRadius) {
            // 摇杆限制在最大半径内
            knobPos.x = direction.x * this.maxRadius;
            knobPos.y = direction.y * this.maxRadius;
        } else {
            // 在最大半径内，摇杆跟随触摸
            knobPos.x = direction.x * distance;
            knobPos.y = direction.y * distance;
        }
        
        // 更新摇杆位置
        this.joystickKnob.setPosition(knobPos);
        
        // 更新小球位置，始终与摇杆保持一致
        if (this.touchBall) {
            this.touchBall.setPosition(knobPos);
        }
    }
    
    private _onTouchEnd(event: EventTouch) {
        if (!this._isTouching || event.getID() !== this._touchId) return;
        
        // 重置触摸状态
        this._touchId = -1;
        this._isTouching = false;
        
        // 重置摇杆位置
        this.joystickBackground.setPosition(this._originPosition);
        this.joystickKnob.setPosition(0, 0, 0);
        
        // 重置小球位置到中心
        if (this.touchBall) {
            this.touchBall.setPosition(0, 0, 0);
        }
        
        // 重置移动向量
        this._moveVector.set(Vec2.ZERO);
    }
    
    update(deltaTime: number) {
        // 移动逻辑将由PlayerController处理
    }
    
    /**
     * 获取当前移动方向(归一化)
     */
    public get moveDirection(): Vec2 {
        return this._moveVector;
    }
    
    /**
     * 检查摇杆是否正在被触摸
     */
    public get isTouching(): boolean {
        return this._isTouching;
    }
    
    /**
     * 获取摇杆的角度(0-360度，0是右，90是上)
     */
    public get angle(): number {
        if (this._moveVector.equals(Vec2.ZERO)) {
            return 0;
        }
        
        let angle = Math.atan2(this._moveVector.y, this._moveVector.x) * 180 / Math.PI;
        if (angle < 0) {
            angle += 360;
        }
        
        return angle;
    }
    
    onDestroy() {
        // 取消注册事件处理程序
        this.node.off(Input.EventType.TOUCH_START, this._onTouchStart, this);
        this.node.off(Input.EventType.TOUCH_MOVE, this._onTouchMove, this);
        this.node.off(Input.EventType.TOUCH_END, this._onTouchEnd, this);
        this.node.off(Input.EventType.TOUCH_CANCEL, this._onTouchEnd, this);
    }
} 